package com.hmdp;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.junit.Test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class PatientSend {

    private ServerSocket serverSocket;
    private ExecutorService executorService;

    public PatientSend() {

    }

    @Test
    @PostConstruct
    public void start() throws IOException {
        serverSocket = new ServerSocket(8888);
        executorService = Executors.newFixedThreadPool(10);
        System.out.println("TCP server started on port 8888");

        while (true) {
            Socket socket = serverSocket.accept();
            executorService.execute(new  ClientHandler(socket));
        }
    }


    @PreDestroy
    public void stop() throws IOException {
        serverSocket.close();
        executorService.shutdown();
    }

    private class ClientHandler implements Runnable {
        private Socket socket;

        public ClientHandler(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String data = reader.readLine();
                System.out.println(data);

                // 解析接收到的JSON格式的患者注册信息
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode jsonNode = objectMapper.readTree(data);

                int id = jsonNode.get("id").asInt();
                String name = jsonNode.get("name").asText();
                String phone = jsonNode.get("phone").asText();
                String password = jsonNode.get("password").asText();
                String publickey = jsonNode.get("publickey").asText();
                System.out.println(id);


                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
